// ==UserScript==
// @match 	        http://*/*
// @name            HTML5 video replacement
// @namespace       media-berry
// @description     Replaces videos to local link starting a native player
// @include         *
// @version         0.7
// ==/UserScript==

// a function that loads jQuery and calls a callback function when jQuery has finished loading
function addJQuery(callback) {
    var script = document.createElement("script");
    // TODO das könnte man noch selber ausliefern ... offline mode !
    script.setAttribute("src", "//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js");
    script.addEventListener('load', function () {
        var script = document.createElement("script");
        script.textContent = "window.jQ=jQuery.noConflict(true);(" + callback.toString() + ")();";
        document.body.appendChild(script);
    }, false);
    document.body.appendChild(script);
}


// the guts of this userscript
function main() {

    // Note, jQ replaces $ to avoid conflicts.
    var playbuttonimage = "";

    jQ("<div id='watch-media-berry-tmp' style='display: none' />").appendTo('body');

    var videotag = jQ("video, #player");

    if (videotag.length > 0) {
        videotag.each(function (index) {

            if (isHtml5(jQ(this))) {
                console.log("Found HTML5 Video")
                // we use the first source tag - maybe we should use mp4
                var src = jQ(this).children("source:first").attr("src");
                src = convertToAbsolute(src);

                // autoplay if it is desired
                var autoplay = jQ(this).attr("autoplay");
                if (typeof autoplay !== 'undefined' && autoplay !== false) {
                    startVideoCmd("play", getLink(src));
                }
            }

            if (isYoutube()) {
                console.log("Found Youtube Video")
                jQ("#guide-main").hide();
                src = jQ(location).attr('href');
            }

            var button = '<div style="width: 250px; margin: auto"><div style="margin-bottom: 5px;border: 8px solid #969696; width: 100%; height: 132px; background: #E0E0E0; border-radius:5px; text-align:center; " class="media-berry-video"><img class="watch-media-berry" alt="' + src + '" style="cursor: pointer;" src="' + playbuttonimage + '"></div><div style="color: black; font-size: 12px; position: absolute; margin-top: -35px; padding-left: 10px;" class="video-options"><span>HDMI sound</span><input class="hdmi" type="checkbox" />&nbsp;&nbsp;<span>Full screen</span><input type="checkbox" class="screen" /></div></div>';

            if (src) {
                jQ(this).hide();
                jQ(this).after(button);

            }

        });
    }


    jQ(".watch-media-berry").click(function () {
        var hdmi = false;
        if (jQ(this).parent().parent().children('.video-options').first().children('.hdmi').first().attr('checked') == "checked") {
            hdmi = true;
        }
        var screen = "window"
        if (jQ(this).parent().parent().children('.video-options').first().children('.screen').first().attr('checked') == "checked") {
            screen = "fullscreen";
        }
        startVideoCmd("play", encodeURIComponent(jQ(this).attr("alt")) + "?hdmi=" + hdmi + "&screen=" + screen + "&youtube=" + isYoutube());
    });


    function isHtml5(tag) {
        console.log(tag.context.tagName.toLowerCase());
        return tag.context.tagName.toLowerCase() == "video";
    }

    function isYoutube() {
        return window.location.hostname == "www.youtube.com";
    }

    function startVideoCmd(key, url) {
        console.log("start video: " + url);
        jQ('<iframe />').attr('src', ' http://localhost:29876/' + key + '/' + url).appendTo("#watch-media-berry-tmp");
    }

    // Dirty to do this here but JQuery seems to do this in further versions
    function convertToAbsolute(link) {
        if(link){
            if (link.indexOf("http") == 0) {
                return link;
            }
            if (link.indexOf(".") != 0) {
                if (link.indexOf("/") == 0) {
                    link = link.substr(1, link.length);
                }
                return getAbsolutePath() + link;
            }
        }
        return null;
    }

    function getAbsolutePath() {
        var loc = window.location;
        var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
        return loc.href.substring(0, loc.href.length - ((loc.pathname + loc.search + loc.hash).length - pathName.length));
    }

}

// load jQuery and execute the main function
addJQuery(main);
